package sysytmRepo

import (
	"gorm.io/gorm"
	"ruoyi/domain/entity/common"
	"ruoyi/domain/entity/response"
	"ruoyi/domain/entity/system"
	"ruoyi/domain/repository"
	"ruoyi/utils"
	"strconv"
)

type SysConfigRepo struct {
	db *gorm.DB
}

func SysConfigRepository(db *gorm.DB) *SysConfigRepo {
	return &SysConfigRepo{db}
}

var _ repository.SysConfigRepository = &SysConfigRepo{}

func (r *SysConfigRepo) SelectConfigList(params common.SearchTableDataParam, isPage bool) common.TableDataInfo {
	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysRoles := params.Other.(system.SysConfig)
	offset := (pageNum - 1) * pageSize
	var total int64
	var rows []system.SysConfig

	var db = r.db.Model(&rows)

	var configId = sysRoles.ConfigId
	if configId != 0 {
		db.Where("config_id = ?", configId)
	}

	var configKey = sysRoles.ConfigKey
	if configKey != "" {
		db.Where("config_key = ?", configKey)
	}

	var configName = sysRoles.ConfigName
	if configName != "" {
		db.Where("config_name like concat('%', ?, '%')", configName)
	}

	var configType = sysRoles.ConfigType
	if configType != "" {
		db.Where("config_type = ?", configType)
	}

	var beginTime = params.Params.BeginTime
	var endTime = params.Params.EndTime

	if beginTime != "" {
		//Loc, _ := time.LoadLocation("Asia/Shanghai")
		//startTime1, _ := time.ParseInLocation(constants.DateFormat, beginTime, Loc)
		//endTime = endTime + " 23:59:59"
		//endTime1, _ := time.ParseInLocation(constants.TimeFormat, endTime, Loc)
		startTime1, endTime1 := utils.GetBeginAndEndTime(beginTime, endTime)
		db.Where("create_time >= ?", startTime1)
		db.Where("create_time <= ?", endTime1)
	}

	if err := db.Count(&total).Error; err != nil {
		return common.Fail()
	}
	if isPage {
		if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
			return common.Fail()
		}
	} else {
		if err := db.Find(&rows).Error; err != nil {
			return common.Fail()
		}
	}

	if rows == nil {
		return common.Fail()
	} else {
		return common.Success(rows, total)
	}
}

func (r *SysConfigRepo) SelectConfig(config system.SysConfig) system.SysConfig {
	var result system.SysConfig
	var dbg = r.db.Model(&result)
	var configId = config.ConfigId
	if configId != 0 {
		dbg.Where("config_id = ?", configId)
	}
	var configKey = config.ConfigKey
	if configKey != "" {
		dbg.Where("config_key = ?", configKey)
	}
	err := dbg.First(&result).Error
	if err != nil {
		panic(response.ReturnFailMsg(err.Error()))
	}
	return result
}

func (r *SysConfigRepo) GetConfigInfo(configId interface{}) system.SysConfig {
	/*方式一*/
	//var sql = "select config_id, config_name, config_key, config_value, config_type, create_by, create_time, update_by, update_time, remark from sys_config where config_id = ?"
	var config system.SysConfig
	//utils.MysqlDb.Raw(sql, configId).Find(&config)
	/*方式二*/
	err := r.db.Where("config_id = ?", configId).First(&config).Error
	if err != nil {
		panic(response.ReturnFailMsg(err.Error()))
	}
	return config
}

func (r *SysConfigRepo) SaveConfig(config system.SysConfig) response.Response {
	/*参数键名是否存在*/
	var keyCount = r.CheckConfigKeyUnique(config.ConfigKey)
	if keyCount > 0 {
		return response.ReturnFailMsg("新增参数'" + config.ConfigName + "'失败，参数键名已存在")
	}
	err := r.db.Model(&system.SysConfig{}).Create(&config).Error
	if err == nil {
		return response.ReturnSuccess("操作成功")
	} else {
		return response.ReturnFailMsg(err.Error())
	}
}

func (r *SysConfigRepo) CheckConfigKeyUnique(configKey string) int64 {
	var keyCount int64
	err := r.db.Model(&system.SysConfig{}).Where("config_key = ?", configKey).Count(&keyCount).Error
	if err != nil {
		panic(response.ReturnFailMsg(err.Error()))
	}
	return keyCount
}

func (r *SysConfigRepo) SelectCaptchaEnabled() bool {
	var configValue = r.SelectConfigByKey("sys.account.captchaEnabled")

	boolValue, err := strconv.ParseBool(configValue)
	if err != nil {
		return true
	}
	return boolValue
}

func (r *SysConfigRepo) SelectConfigByKey(configKey string) string {
	var config system.SysConfig
	err := r.db.Where("config_key = ?", configKey).First(&config).Error
	if err != nil {
		panic(response.ReturnFailMsg(err.Error()))
	}
	return config.ConfigValue
}

func (r *SysConfigRepo) EditConfig(config system.SysConfig) response.Response {
	err := r.db.Updates(&config).Error
	if err == nil {
		return response.ReturnSuccess("操作成功")
	} else {
		return response.ReturnFailMsg(err.Error())
	}
}

func (r *SysConfigRepo) DelConfig(configIds string) response.Response {
	var ids = utils.Split(configIds)
	for i := 0; i < len(ids); i++ {
		id := ids[i]
		var config = r.GetConfigInfo(id)
		configType := config.ConfigType
		if "Y" == configType {
			panic(response.ReturnFailMsg("内置参数" + config.ConfigKey + "不能删除 "))
		}
		r.DelConfigById(config.ConfigId)
	}
	return response.ReturnSuccess("操作成功")
}

func (r *SysConfigRepo) DelConfigById(configId int) {
	err := r.db.Where("config_id = ?", configId).Delete(&system.SysConfig{}).Error
	if err != nil {
		panic(response.ReturnFailMsg(err.Error()))
	}
}
